<?php

namespace app\admin\controller\expert;

use app\common\controller\Backend;
use fast\Tree;
use think\Cache;

/**
 * 上下级关系管理
 *
 * @icon   fa fa-list
 * @remark 
 */
class Relation extends Backend
{

    protected $searchFields = 'u.nickname,u.mobile';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 列表
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list_info = db("expert_relation er")
                ->join('user u', "er.user_id=u.id", "LEFT")
                ->join('user u2', "er.up_user_id=u2.id", "LEFT")
                ->field("er.*,u.nickname,u.avatar,u.mobile,u2.nickname as parent_nickname,u2.avatar as parent_avatar,u2.mobile as parent_mobile,u2.expire_times")
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $list = $list_info->items();
            $total = $list_info->total();
            foreach ($list as $k => $v) {
                // exit(print_r($v));
                $list[$k]["avatar"] = $v["avatar"] ? cdnurl($v["avatar"], true) : letter_avatar($v["nickname"]);
                $list[$k]["parent_avatar"] = $v["parent_avatar"] ? cdnurl($v["parent_avatar"], true) : letter_avatar($v["parent_nickname"]);
                unset($list[$k]["password"]);
                unset($list[$k]["salt"]);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 隐藏关系
     */
    public function hide_relation()
    {
        $ids = $this->request->param("ids");
        $expert_relation = db("expert_relation")->where("id", $ids)->find();
        if (!$expert_relation) {
            $this->error("找不到记录");
        }

        $result = db("expert_relation")->where("id", $expert_relation["id"])->update(["status" => 0]);
        if ($result === false) {
            $this->error("更新失败");
        }
        $this->success("更新成功");
    }

    /**
     * 打开关系
     */
    public function open_relation()
    {
        $ids = $this->request->param("ids");
        $expert_relation = db("expert_relation")->where("id", $ids)->find();
        if (!$expert_relation) {
            $this->error("找不到记录");
        }

        $result = db("expert_relation")->where("id", $expert_relation["id"])->update(["status" => 1]);
        if ($result === false) {
            $this->error("更新失败");
        }
        $this->success("更新成功");
    }
}
